package utils;

import jdbc.DataSource;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

/*
* JDK动态代理
* */
public class ConnectionHandler implements InvocationHandler{
    private DataSource dataSource;
    private Connection realConn;
    private Connection conn;

    public ConnectionHandler(DataSource dataSource){
        this.dataSource = dataSource;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if ("close".equals(method.getName())) {
            dataSource.free(conn);
            return null;
            // target.close();
        }else {
            return method.invoke(realConn, args);
        }
    }

    public Object bind(Object target){
        /*
        * 绑定委托对象，返回代理对象
        * */
        this.realConn = (Connection) target;
        conn = (Connection) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),
                this);
        return conn;
    }
}
